package com.star.spring.deferred.controller;


import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @description: 异步编程demo
 * @author: star
 * @create: 2024-12-16 15:39
 **/

@RestController()
@RequestMapping("/deferred")
public class DeferredController {

    /**
     * hello world
     *
     * @return 结果
     */
    @GetMapping("/hello")
    public DeferredResult<String> test() {

        // 打印日志
        Logger logger = Logger.getLogger("DeferredController");
        DeferredResult<String> result = new DeferredResult<>(5000L, HttpStatus.NOT_MODIFIED);

        result.onTimeout(() -> {
            logger.log(Level.INFO, "超时了");
            result.setErrorResult("timeout");
        });

        result.onCompletion(() -> {
            logger.log(Level.INFO, "完成");
            result.setResult("success");
        });

        new Thread(() -> {
            try {
                Thread.sleep(10000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            result.setResult("hello world");
        }).start();
        return result;

    }
}
